#include <iostream>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Common.hpp"
#include "Log.hpp"
#include "ThreadPool.hpp"
#include <string.h>
#include "InetAddr.hpp"
#include <functional>

#define BACKLOG 10
#define GLOBAL_PORT 8082
using namespace LogMudule;
using namespace ThreadPoolModule;

using task_t = std::function<void()>;
using handler_t = std::function<std::string(std::string &)>;

class TcpServer
{
public:
    TcpServer(handler_t handler, int port = GLOBAL_PORT) : _listensockfd(-1), _isrunning(false), _port(port), _handler(handler)
    {
    }

    void InitServer()
    {
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create socket failed";
            Die(SOCKET_ERR);
        }

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);

        int n = ::bind(_listensockfd, CONV(&local), len);
        if (n != 0)
        {
            LOG(LogLevel::FATAL) << "bind listensockfd failed";
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd is : " << _listensockfd;

        n = ::listen(_listensockfd, BACKLOG);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd is : " << _listensockfd;
    }

    void HandlerRequest(int sockfd)
    {
        // 采用recv和send，默认flag为0
        std::string packge;
        char inbuffer[4096];
        while (true)
        {
            // 约定：用户发过来的是一个完整的命令string
            // ssize_t n = ::read(sockfd, inbuffer, sizeof(inbuffer) - 1); // read读取是不完善
            ssize_t n = ::recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0); // recv读取是不完善
            if (n > 0)
            {
                inbuffer[n] = 0;
                LOG(LogLevel::INFO) << "\n" << inbuffer;
                packge += inbuffer; // ?? // len\r\n{json}\r\n

                // std::string echo_str = "server echo# ";
                // echo_str += inbuffer;

                std::string cmd_result = _handler(packge);
                if(cmd_result.empty()) continue; //TODO

                ::send(sockfd, cmd_result.c_str(), cmd_result.size(), 0); // 写入也是不完善
            }
        }
        ::close(sockfd); // fd泄漏问题！
    }
    /*void HandlerRequest(int sockfd) // TCP也是全双工通信的
    {
        LOG(LogLevel::INFO) << "HandlerRequest, sockfd is : " << sockfd;
        char inbuffer[4096];
        std::string package; // vector<char>
        // 长任务
        while (true)
        {
            // 约定：用户发过来的是一个完整的命令string
            // ssize_t n = ::read(sockfd, inbuffer, sizeof(inbuffer) - 1); // read读取是不完善
            ssize_t n = ::recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0); // recv读取是不完善
            if (n > 0)
            {
                inbuffer[n] = 0;
                LOG(LogLevel::INFO) << "\n" << inbuffer;
                package += inbuffer; // ?? // len\r\n{json}\r\n

                // std::string echo_str = "server echo# ";
                // echo_str += inbuffer;

                std::string cmd_result = _handler(package);
                if(cmd_result.empty()) continue; //TODO

                ::send(sockfd, cmd_result.c_str(), cmd_result.size(), 0); // 写入也是不完善
            }
            else if (n == 0)
            {
                // read 如果读取返回值是0，表示client退出
                LOG(LogLevel::INFO) << "client quit: " << sockfd;
                break;
            }
            else
            {
                // 读取失败了
                break;
            }
        }
        ::close(sockfd); // fd泄漏问题！
    }*/

    void Start()
    {
        _isrunning = true;
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t len = sizeof(peer);
        while (_isrunning)
        {
            // accept客户端，为每一个客户端创建socked
            int sockfd = ::accept(_listensockfd, CONV(&peer), &len);
            InetAddr id(peer);

            LOG(LogLevel::INFO) << "create sockfd: " << sockfd;
            LOG(LogLevel::INFO) << "新来client: " << id.ID();

            task_t f = std::bind(&TcpServer::HandlerRequest, this, sockfd);
            ThreadPool<task_t>::getInstance()->Equeue(f);
        }
    }

    ~TcpServer()
    {
    }

private:
    int _listensockfd;
    bool _isrunning;
    int _port;

    handler_t _handler;
};
